package com.sk.bilibili.websocket;

import com.sk.bilibili.bean.Danmu;
import com.sk.bilibili.decoder.DanmuDecoder;
import com.sk.bilibili.encoder.JsonEncoder;
import com.sk.bilibili.service.LiveSocketService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

/**
 * @author 邵康
 * @date 2021/12/2 14:07
 */
@Component
@ServerEndpoint(value = "/live/{liveId}",encoders = JsonEncoder.class,
        decoders = DanmuDecoder.class)
public class LiveSocket {

    private static LiveSocketService liveSocketService;
    private Integer liveId;

    @Autowired
    public void setLiveSocketService(LiveSocketService liveSocketService) {
        LiveSocket.liveSocketService = liveSocketService;
    }

    @OnMessage
    public void onMessage(Danmu danmu){
        liveSocketService.broadcastDanmu(liveId,danmu);
    }

    @OnOpen
    public void onOpen(@PathParam("liveId")Integer liveId,Session session){
        liveSocketService.addNew(liveId,session);
        this.liveId=liveId;
    }

    @OnError
    public void onError(Throwable e){
        e.printStackTrace();
    }

    @OnClose
    public void onClose(Session session){
        liveSocketService.removeOld(liveId,session);
    }

}
